<?php
/**
 * Created by PhpStorm.
 * User: jinqiang
 * Date: 2019/8/5
 * Time: 20:19
 */

namespace App\Http\Repository;


use App\Http\Models\Mysql\NnyyUserTable;
use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class CommonRepository
{
    const USERKEY = ["toQQ","toWechat",'toFriends','tmall','jd','pdd','sn'];
    const TOKENREG = "/(￥|₤|\\$|₴|₳|￠|¢|€|\\(|（){1,}[0-9a-zA-Z]{11,}(￥|₤|\\$|₴|₳|￠|¢|€|\\)|）){1,}/is";
    const HTTPREG = "/((?:https?:\/\/|u\\.jd\\.com)[a-zA-Z0-9\w\\+.-\/\\\?=&%{}\[\]:;-]+)/is";

    //获取用户信息 name, domain_name, qq
    public function getUserInfo($value, $type='name')
    {
        $user = (new NnyyUserTable())->where($type, $value)->first();
        if (empty($user)) {
            return ['code' => -1, 'msg' => '无效用户'];
        }
//        $now = time();
//        if(strtotime($user->effect_time) < $now){
//            return ['code' => -1, 'msg' => "亲, 您的使用期限已过期, 感谢您的一路陪伴与支持!"];
//        }
        return ['code' => 0, 'data' => $user->toArray()];
    }

    //发送邮件
    public function sendMail($to, $subject, $message=['node' => 'test'], $mailTemplate='mail.wechat')
    {
        Mail::send($mailTemplate, $message, function ($message) use($to, $subject) {
            $message->to($to)->subject($subject);
        });
        if(count(Mail::failures()) < 1){
            return true;
        }else{
            return false;
        }
    }

    //上传cdn静态资源服务器 qiniu oss
    public function uploadCDN($url, $type='oss')
    {
        try{
            //指定存储磁盘
            $disk = Storage::disk($type);
            $fileName = md5($url).".jpg";
            $cdnDomain = env('QINIU_DOMAIN');
            if($type=='oss'){
                $cdnDomain = env('ALIYUN_CDN_DOMAIN');
            }
            $imgFile = $cdnDomain . $fileName;
            if($disk->exists($fileName)){
                return ['code' => 0, 'img' => $imgFile, 'msg' => 'exists'];
            }
            $opts = array(
                'http'=>array(
                    'method'=>"GET",
                    'timeout'=>2,//单位秒
                )
            );
            $i=0;
            while($i<3 && ($content=@file_get_contents($url, false, stream_context_create($opts)))===FALSE){
                $i++;
                usleep(500000);
            }
            if(empty($content)){
                return ['code' => -1, 'msg' => "获取链接内容失败"];
            }
            $isPut = $disk->put($fileName, $content);
            if($isPut){
                return ['code' => 0, 'img' => $imgFile];
            }
        }catch (Exception $e){
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
        return ['code' => -1, 'msg' => "保持图片失败"];
    }

    //短链服务
    public function shortUrl($longUrl, $mode="heytmall")
    {
        switch ($mode){
            case "sina":
                $url = ShortUrlRepository::sina($longUrl);
                if($longUrl==$url){
                    $url = ShortUrlRepository::heytmall($longUrl);
                }
                return $url;
            case "heytmall":
                $url = ShortUrlRepository::heytmall($longUrl);
                return $url;
            case "weixin":
                $url = ShortUrlRepository::weixin($longUrl);
                if($longUrl==$url){
                    $url = ShortUrlRepository::heytmall($longUrl);
                }
                return $url;
        }
    }

    //客户端ip访问限制
    public static function detectClientId($clientId, $num = 10)
    {
        info("CLIENT_IP", [$clientId]);
        $requestNum = Cache::get($clientId) ?: 1;
        if($requestNum > $num){
            return ['code'=>-1, 'msg' => "操作过于频繁"];
        }else{
            $requestNum += 1;
            Cache::put($clientId, $requestNum, Carbon::now()->addMinutes(30));
        }
        return ['code'=> 0];
    }
}
